/*
 * File Name：ImagePagerAdapter.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： ImagePagerAdapter.java
 * Modify By：bin
 * Modify Date：2015年1月16日
 * Modify Type：Add
 */
package com.ciwong.mobilelib.adapter;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.URLUtil;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.mobilelib.R;
import com.ciwong.mobilelib.ui.ScanImageActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.BaseUtils;
import com.ciwong.mobilelib.utils.ImageLoaderHelper;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * 
 * 
 * @author bin
 * @version ciwong v.1.0 2015年1月16日
 * @since ciwong v.1.0
 */
public class ImagePagerAdapter extends PagerAdapter
{
    private List<String> mResources;

    private Activity mContext;

    private int mCurrentPosition = -1;

    private int mLastPosition = -1;

    private DisplayImageOptions mOptions;

    // private Map<String, PhotoView> mImageViews = new LinkedHashMap<String,
    // PhotoView>();
    //
    // private Map<String, Bitmap> mBitMap = new LinkedHashMap<String,
    // Bitmap>();

    private Map<Integer, Bitmap> mBitmaps = new HashMap<Integer, Bitmap>();

    private int THUMBNAIL_HEIGHT = 1100;

    private View mCurView;

    /**
     * 
     * 构造函数
     * 
     */
    public ImagePagerAdapter()
    {
        mResources = null;
        mOptions = BaseConstants.getDisplayBuilder().build();
        THUMBNAIL_HEIGHT = DeviceUtils.getScreenHeight();
        if (THUMBNAIL_HEIGHT >= 1100)
        {
            THUMBNAIL_HEIGHT = 1100;
        }
    }

    /**
     * 
     * 构造函数
     * 
     * @param context
     *            上下文
     * @param resources
     *            图片地址
     */
    public ImagePagerAdapter(Activity context, List<String> resources)
    {
        this();
        this.mResources = resources;
        this.mContext = context;
        THUMBNAIL_HEIGHT = DeviceUtils.getScreenHeight();
        if (THUMBNAIL_HEIGHT >= 1100)
        {
            THUMBNAIL_HEIGHT = 1100;
        }
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position)
    {
        View view = initContainer(container, position);
        return view;
    }

    private View initContainer(ViewGroup container, final int position)
    {
        Log.i("curTime",
                System.currentTimeMillis() + "instantiateItem" + position);
        RelativeLayout rlContainer = new RelativeLayout(mContext);
        final PhotoView photoView = new PhotoView(mContext);
        Drawable drawable = mContext.getResources()
                .getDrawable(R.color.scan_image_color);
        photoView.setImageDrawable(drawable);
        // 初始化看图view的触摸事件
        initEventForPhotoView(photoView);

        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        rlContainer.addView(photoView, 0, params);

        // 初始化进度圈
        final ProgressBar pBar = (ProgressBar) mContext.getLayoutInflater()
                .inflate(R.layout.layout_widget_progress_bar, null);
        pBar.setVisibility(View.VISIBLE);
        // pBar.setMinimumHeight(DeviceUtils.dip2px(20));
        // pBar.setMinimumWidth(DeviceUtils.dip2px(20));
        // pBar.setIndeterminate(false);
        // drawable = mContext.getResources().getDrawable(
        // R.drawable.libs_loading_progress);
        // pBar.setIndeterminateDrawable(drawable);
        params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        rlContainer.addView(pBar, 1, params);

        container.addView(rlContainer, LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);

        if (position != mCurrentPosition)
        {
            new Handler().postDelayed(new Runnable()
            {
                public void run()
                {
                    loadImage(photoView, pBar, position);
                }
            }, 1000);
        }
        else
        {
            new Handler().postDelayed(new Runnable()
            {
                public void run()
                {
                    loadImage(photoView, pBar, position);
                }
            }, 1000);
        }
        return rlContainer;
    }

    /**
     * 加载图片
     * @param imageView
     * @param pBar
     * @param position
     */
    public void loadImage(final PhotoView imageView, final ProgressBar pBar,
            final int position)
    {
        final String path = mResources.get(position);
        if (BaseUtils.isTCPFileFormat(path) || URLUtil.isHttpUrl(path))
        {
            ImageLoaderHelper.getInstance().displayImage(path, imageView,

                    new ImageSize(THUMBNAIL_HEIGHT, THUMBNAIL_HEIGHT), mOptions,
                    new ImageLoadingListener()
                    {
                        @Override
                        public void onLoadingStarted(String s, View view)
                        {

                        }

                        @Override
                        public void onLoadingFailed(String s, View view,
                                FailReason failReason)
                        {
                            pBar.setVisibility(View.GONE);
                        }

                        @Override
                        public void onLoadingComplete(String s, View view,
                                Bitmap bitmap)
                        {
                            pBar.setVisibility(View.GONE);
                            int size = bitmap.getRowBytes()
                                    * bitmap.getHeight();
                            mBitmaps.put(position, bitmap);
                            Log.i("curTime", System.currentTimeMillis()
                                    + "loadImage" + position);
                        }

                        @Override
                        public void onLoadingCancelled(String s, View view)
                        {

                        }
                    });
        }
        else
        {
            // 图片地址
            ImageLoader.getInstance().displayImage(path,
                    new ImageViewAware(imageView), mOptions,
                    new ImageLoadingListener()
                    {

                        @Override
                        public void onLoadingStarted(String s, View view)
                        {
                        }

                        @Override
                        public void onLoadingFailed(String s, View view,
                                FailReason failReason)
                        {
                            pBar.setVisibility(View.GONE);
                        }

                        @Override
                        public void onLoadingComplete(String s, View view,
                                Bitmap bitmap)
                        {
                            pBar.setVisibility(View.GONE);

                            if (null != bitmap) {
                                int size = bitmap.getRowBytes()
                                        * bitmap.getHeight();
                                mBitmaps.put(position, bitmap);
                                Log.i("curTime", System.currentTimeMillis()
                                        + "loadImage" + position);
                            }
                        }

                        @Override
                        public void onLoadingCancelled(String s, View view)
                        {

                        }
                    });
        }
    }

    /**
     * 
     * 回收方法
     * 
     */
    public void recycle()
    {
        synchronized (mBitmaps)
        {
            Set<Integer> keys = mBitmaps.keySet();
            // Log.i("se7en", keys.size() + "");
            // ((com.ciwong.xixinbase.ui.BaseActivity) mContext)
            // .showToastSuccess("bitmap的数量=" + keys.size() + "");
            for (Integer i : keys)
            {
                Bitmap bm = mBitmaps.get(i);
                if (bm != null && !bm.isRecycled())
                {
                    bm.recycle();
                    bm = null;
                }
            }
            mBitmaps.clear();
        }
    }

    /**
     * 
     * {@inheritDoc}
     */
    @Override
    public void destroyItem(ViewGroup collection, int position,
            Object photoView)
    {
        mBitmaps.remove(position);
        clearBitmapFromPhotoView((RelativeLayout) photoView);
        collection.removeView((View) photoView);
    }

    private void clearBitmapFromPhotoView(RelativeLayout rl)
    {
        PhotoView photoView = (PhotoView) rl.getChildAt(0);
        if (photoView != null)
        {
            Drawable drawable = (Drawable) (photoView.getDrawable());
            if (drawable != null && drawable instanceof BitmapDrawable)
            {
                Bitmap bm = ((BitmapDrawable) drawable).getBitmap();
                Set<Integer> keys = mBitmaps.keySet();
                for (Integer i : keys)
                {
                    if (mBitmaps.get(i) == bm)
                    {
                        return;
                    }
                }
                if (bm != null && !bm.isRecycled())
                {
                    bm.recycle();
                    bm = null;
                }
            }
        }
    }

    @Override
    public int getCount()
    {
        return mResources.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object)
    {
        return view.equals(object);
    }

    public int getCurrentPosition()
    {
        return mCurrentPosition;
    }

    public void setCurrentPosition(int position)
    {
        this.mCurrentPosition = position;
    }

    public List<String> getAllResources()
    {
        return mResources;
    }

    private void initEventForPhotoView(PhotoView photoView)
    {
        PhotoViewAttacher attacher = photoView.getAttacher();
        ScanImageActivity scanImageActivity = (ScanImageActivity) mContext;
        scanImageActivity.initEventForMattacher(attacher);
    }
}
